import React, {FC, useEffect, useMemo, useRef} from "react";
import useStateRef from "@core/customUse/useStateRef";
import {InputNumber} from "antd";
import {useTranslation} from "react-i18next";
import "./css/InputDayAndHour.less";

interface InputDayAndHourProps {
    value: string,
    ds: any,
    onChange: Function
}

const InputDayAndHour: FC<InputDayAndHourProps> = (props) => {
    const {t} = useTranslation();

    const valuesRef = useRef([0, 0])

    const [values, setValues] = useStateRef(undefined, valuesRef);

    useEffect(() => {
        const {ds = {}}: { ds?: any } = props;
        let newValue = ds.value !== undefined ? ds.value : props.value;
        if (newValue && JSON.stringify(newValue) !== JSON.stringify(valuesRef.current.join("-"))) {
            setValues(newValue.split("-"))
        }
    }, [props.ds])

    useEffect(() => {
        if (values) {
            props.onChange && props.onChange(values.join("-"));
        }
    }, [JSON.stringify(values)]);

    const renderInputDayAndHour = useMemo(() => {
        const value = values || [0, 0];
        return (<div className="bams_core_input_day_and_hour">
            <InputNumber value={value[0]} onChange={(value: number) => {
                setValues([value, valuesRef.current[1]])
            }} className="bams_core_input_day_and_hour_input"/>
            <span style={{margin: "0 5px"}}>{t("days")}</span>
            <InputNumber value={value[1]} onChange={(value: number) => {
                setValues([valuesRef.current[0], value])
            }} className="bams_core_input_day_and_hour_input" min={0} max={24}/>
            <span style={{marginLeft: "5px"}}>{t("hour")}</span>
        </div>)
    }, [values]);

    return (renderInputDayAndHour);
};

export default React.memo(InputDayAndHour);